const { CommandInteraction, MessageEmbed } = require('discord.js');

module.exports = {
  name: 'clear',
  description:
    'Deletes a specified numbe of messages from a channel or a target.',
  permission: 'MANAGE_MESSAGES',
  options: [
    {
      name: 'amount',
      description:
        'Select the amount of messages to delete from a channel or a target.',
      type: 'NUMBER',
      required: true,
    },
    {
      name: 'target',
      description: 'Select the target to clear their messages.',
      type: 'USER',
      required: false,
    },
  ],
  /**
   *
   * @param {CommandInteraction} interaction
   */
  async execute(interaction) {
    const { channel, options } = interaction;

    const amount = options.getNumber('amount');
    const target = options.getMember('target');

    const messages = await channel.messages.fetch();
    const Responce = new MessageEmbed().setColor('DARK_VIVID_PINK');

    if (target) {
      let i = 0;
      const filtered = [];
      (await messages).filter(m => {
        if (m.author.id === target.id && i < amount) {
          filtered.push(m);
          i++;
        }
      });

      await channel.bulkDelete(filtered, true).then(m => {
        Responce.setDescription(`🧹 Cleared ${m.size} messages from ${target}`);
        interaction.reply({ embeds: [Responce] });
      });
    } else {
      await channel.bulkDelete(amount, true).then(m => {
        Responce.setDescription(
          `🧹 Cleared ${m.size} messages from this channel`
        );
        interaction.reply({ embeds: [Responce] });
      });
    }
  },
};
